<?php
class data_cron extends page{
	
	private $fileDir = '';
	private $infoDir = '';
	private $outDir = '';
	private $bucket = '';
	private $oss_folder = '';
	
	function __construct(){
		parent::__construct();
		
		$this->filedir = dirname(dirname(__FILE__));
		$this->infoDir = $this->filedir.'/book/info/';
		$this->outDir = $this->filedir.'/book/out/';
		$this->bucket = 'shuqi';
		$this->oss_folder = '78';
	}
	
	function bookInfoToDB(){
		if (is_dir($this->infoDir)) {
			if ($dh = opendir($this->infoDir)) {
				while (($file = readdir($dh)) !== false) {
					if ($file!="." && $file!=".." && $file!=".svn") {
						$l = explode('.', $file);
						$bookID = $l[0];	// book name
						
						$s = file_get_contents($this->infoDir.$file);
						$bookInfo = json_decode($s, true);
						
						$cateId = $bookInfo['cateId'];
						$cateName = $bookInfo['cateName'];
						$last = $bookInfo['last'];
						$title = $bookInfo['title']?$bookInfo['title']:'';
						$author = $bookInfo['author']?$bookInfo['author']:'';
						$desc = $bookInfo['desc']?$bookInfo['desc']:'';
						
						if(!$title || !$author){	//	if missing title or author ignore this book
							file_put_contents($this->outDir.'/../insert_error.log', $file."\n", FILE_APPEND);
							continue;
						}
						
						$select_sql = "select count(*) as c, id from book where title='{$title}'";
						$select_rs = $this->db->query($select_sql)->fetch();
						$time = date('Y-m-d H:i:s', time());
						if($select_rs['c']){
							$update_sql = "update book set last='{$last}' where id={$select_rs['id']} ";
							$update_rs = $this->db->exec($update_sql);
							
							file_put_contents($this->outDir.'/../update.log', $title."||Time:".$time."\n", FILE_APPEND);
						}else{
							$file = $this->getOSSUrl($bookID);
							$insert_sql = "insert into book (title, summary, author, cateId, cateName, file, last, create_time) values ('{$title}','{$desc}','{$author}','{$cateId}','{$cateName}','{$file}','{$last}', now())";
							$insert_rs = $this->db->exec($insert_sql);
							
							file_put_contents($this->outDir.'/../insert.log', $title."||Time:".$time."\n", FILE_APPEND);
						}
					}
				}
				require_once ROOT.'/book/GBook.php';	// 清空info文件夹
				$GBookClass = new GBook();
				$GBookClass->deleteFileOfDir($this->infoDir);
			}
		}
	}
	
	public function getCateList(){
		
		$select_sql = "select cateId, cateName from book group by cateId order by cateId";
		$select_rs = $this->db->query($select_sql)->fetchAll();
		if($select_rs){
			foreach($select_rs as $row){
				$cateId = $row['cateId'];
				$cateName = $row['cateName'];
				
				$insert_sql = "insert into cate (cateId, cateName) values ('{$cateId}', '{$cateName}')";
				$this->db->exec($insert_sql);
			}
		}
		
		echo "Done!\n";
	}
	
	public function runTask(){
		
		$select_sql = "select * from task where task_status = 1 limit 50";
		$select_rs = $this->db->query($select_sql)->fetchAll();
		
		if(!$select_rs){
			echo 'Empty list!';
			exit;
		}
		
		$ids = array();
		$taskList = array();
		foreach ($select_rs as $row){
			$id = $row['id'];
			$ids[] = $id;
			$taskList[$id]['content'] = $row['content'];
			$taskList[$id]['type'] = $row['type'];
			$taskList[$id]['task_status'] = $row['task_status'];
			$taskList[$id]['status'] = $row['status'];
			$taskList[$id]['update'] = $row['update_time'];
		}
		
		if(!empty($ids)){	
			$idString = implode(',', $ids);
			$update_sql = "update task set task_status = 2 where id in ({$idString})";
			$this->db->exec($update_sql);
		}
		
		require_once ROOT.'/book/GBook.php';
		$GBookClass = new GBook();
		$doIDs = array();
		foreach ($taskList as $taskId => $task){
			$t = time();
			$now = date('Y-m-d H:i:s', $t);
			
			if($task['type']==2){	// 当任务为更新书本时
				$select_book_sql = "select title, update_time from book where id='{$task['content']}'";
				$s_book=$this->db->query($select_book_sql)->fetch();
				$u_time = strtotime($s_book['update_time']);
				if($t-$u_time<=1800)continue;	// ignore 30分钟内有改动的书本
				$task['content']=$s_book['title'];
			}
			
			$term = mb_convert_encoding($task['content'], 'gb2312','auto');
			$doReturn = $GBookClass->search($term);
			if($doReturn)$doIDs[]=$taskId;
			
			file_put_contents(ROOT.'/book/out/run_task.log', 'Action:Search||'.$now.'||'.$task['content']."\n", FILE_APPEND);
		}
		$GBookClass->spiltBook();
		
		if(!empty($doIDs)){
			$doIDsString = implode(',', $doIDs);
			$update_do_sql = "update task set status = 2, task_status = 0 where id in ({$doIDsString})";
			$this->db->exec($update_do_sql);
		}

		$unDoIds = array_diff($ids, $doIDs);
		if(!empty($unDoIds)){
			$unDoIdsString = implode(',', $unDoIds);
			$update_undo_sql = "update task set task_status = 1 where id in ({$unDoIdsString})";
			$this->db->exec($update_undo_sql);
		}
		
		echo "Do Search Task Cron Done!\n";
		
		$this->bookInfoToDB();
		echo "Start book info to DB Task!\n";
	}
	
	public function checkVIP(){
		$today = date('Y-m-d', time());
		
		$update_sql = "UPDATE vip SET is_vip=0 WHERE end_time<'{$today}' AND is_vip=1";
		$this->db->exec($update_sql);
		
		echo "check VIP Done.\n";
	}
	
	public function moveTask(){
//		$sql = "select * from task where ";		


	}
	

	/***********************************************************************************************/

	/**
	 * example : http://shuqi.oss.aliyuncs.com/78/10015.zip
	 * 
	 * @param String $file
	 */
	private function getOSSUrl($file){
		if(!$file)return false;
		return "http://{$this->bucket}.oss.aliyuncs.com/{$this->oss_folder}/{$file}.zip";
	}
	
}
